package com.litchishell.easy;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author LitchiShell
 * @description: 题目14：最长公共前缀
 * @create 2022-08-18
 */
public class Solution004 {

    // 常规解法
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length < 1) {
            return "";
        }
        if (strs.length == 1) {
            return strs[0];
        }
        // 获取最小字符串长度
        int minLength = getMinLength(strs);

        String result = "";
        List<String> list = new ArrayList<>();
        for (int i = 0; i < minLength; i++) {
            Set<String> set = new HashSet<>();
            for (int i1 = 0; i1 < strs.length; i1++) {
                set.add(strs[i1].substring(i, i + 1));
            }
            if (set.size() == 1) {
                list.addAll(new ArrayList<>(set));
            } else {
                break;
            }
        }
        for (String s : list) {
            result = result + s;
        }
        return result;
    }

    private static int getMinLength(String[] strs) {
        int temp = strs[0].length();
        for (String str : strs) {
            if (str.length() <= temp) {
                temp = str.length();
            }
        }
        return temp;
    }

    // 官方题解
    public String longestCommonPrefixCopy(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            prefix = longestCommonPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    public String longestCommonPrefix(String str1, String str2) {
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        while (index < length && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        return str1.substring(0, index);
    }

    public static void main(String[] args) {
        String[] strs = new String[] {"ac", "a"};
        System.out.println(longestCommonPrefix(strs));
    }
}
